<template>
  <a-modal :open="open" width="930px" :title="formState?.id ? '修改供应商' : '新增供应商'" centered :footer="false" @cancel="onCancel">
    <a-tabs v-model:activeKey="tabActiveKey" class="tab-overflow">
      <a-tab-pane key="1" tab="基本信息">
        <a-form :model="formState" name="validate_other" class="form-style-flex" :label-col="{ style: { width: '95px' } }">
          <a-form-item name="supplierName" label="供应商名称" class="w-1/2" :rules="[{ required: true, message: '请输入供应商名称' }]">
            <a-input v-model:value="formState.supplierName" placeholder="请输入" @blur="getPyjm(formState.supplierName)" />
          </a-form-item>

          <a-form-item name="zjm" label="助记码" class="w-1/2" :rules="[{ required: true, message: '请输入助记码' }]">
            <a-input v-model:value="formState.zjm" placeholder="请输入" />
          </a-form-item>

          <a-form-item name="contactPerson" label="联系人" class="w-1/2">
            <a-input v-model:value="formState.contactPerson" placeholder="请输入" />
          </a-form-item>

          <a-form-item name="contactPhone" label="联系电话" class="w-1/2">
            <a-input v-model:value="formState.contactPhone" placeholder="请输入" />
          </a-form-item>

          <a-form-item name="address" label="联系地址" class="w-1/2">
            <a-input v-model:value="formState.address" placeholder="请输入" />
          </a-form-item>

          <a-form-item name="postcode" label="邮政编码" class="w-1/2">
            <a-input v-model:value="formState.postcode" placeholder="请输入" />
          </a-form-item>

          <a-form-item name="bankName" label="开户银行" class="w-1/2">
            <SelectItem v-model:value="formState.bankName" type="DT00018" placeholder="请选择" />
          </a-form-item>

          <a-form-item name="bankAccount" label="账户" class="w-1/2">
            <a-input v-model:value="formState.bankAccount" placeholder="请输入" />
          </a-form-item>
          <a-form-item label="备注" class="w-full">
            <a-textarea v-model:value="formState.memo" :rows="7" placeholder="请输入" />
          </a-form-item>
        </a-form>
        <a-space class="flex justify-end p-4">
          <a-button @click="onCancel">取消</a-button>
          <a-button type="primary" :disabled="!formState.supplierName || !formState.zjm" @click="onOk">保存</a-button>
        </a-space>
      </a-tab-pane>
      <a-tab-pane key="2" tab="首营资质" :disabled="!formState.id">
        <div class="flex">
          <div class="w-1/2">
            <BaseTable
              column-code="000084"
              :data-source="tableData"
              :custom-row="
                (record) => ({
                  onClick: () => {
                    selectedRowKey = record.dictCommonCode
                  }
                })
              "
              :row-class-name="(record) => (record.dictCommonCode === selectedRowKey ? 'selected-row' : '')"
              :loading="loading"
              :height="300"
              bordered
            >
              <template #bodyCell="{ column, index, record }">
                <template v-if="column.dataIndex == 'xh'">
                  {{ index + 1 }}
                </template>
                <template v-if="column.dataIndex == 'status'">
                  <a-tag :color="record.status === '未维护' ? 'red' : 'green'">{{ record.status }}</a-tag>
                </template>
              </template>
            </BaseTable>
          </div>
          <div class="w-1/2 pr-2">
            <a-form :model="formBattalion" name="validate_other" :label-col="{ style: { width: '95px' } }">
              <a-form-item name="certificateNo" label="证书编号" :rules="[{ required: true, message: '请输入证书编号' }]">
                <a-input v-model:value="formBattalion.certificateNo" class="w-[320px]" placeholder="请输入" />
              </a-form-item>
              <a-form-item name="dateRange" label="证书有效期" :rules="[{ required: true, message: '请输入证书编号' }]">
                <a-range-picker v-model:value="formBattalion.dateRange" class="w-[320px]" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
              </a-form-item>
              <a-form-item label="备注" class="w-full">
                <a-textarea v-model:value="formBattalion.memo" class="w-[320px]" :rows="1" placeholder="请输入" />
              </a-form-item>
              <a-form-item name="image" label="上传证书" class="w-full" :rules="[{ required: true, message: '' }]">
                <div class="clearfix">
                  <a-upload v-model:file-list="fileList" list-type="picture-card" :custom-request="beforeUpload" @preview="handlePreview">
                    <div v-if="fileList.length !== 3">
                      <PlusOutlined />
                      <div style="margin-top: 8px">上传图片</div>
                    </div>
                  </a-upload>
                  <a-modal :open="previewVisible" width="70%" :footer="null" @cancel="handleCancel">
                    <!-- <div class="flex justify-end pr-16">
                      <UndoOutlined class="cursor-pointer" style="font-size: 20px" @click="handlerRotate" />
                    </div> -->
                    <div class="w-full h-full mt-6">
                      <img
                        alt="example"
                        style="width: 100%; height: 100%; transition: transform 0.5s"
                        :style="{ transform: `rotate(${rotateDegree}deg)` }"
                        :src="previewImage"
                      />
                    </div>
                  </a-modal>
                </div>
              </a-form-item>
            </a-form>
          </div>
        </div>
        <a-space class="flex justify-end p-4">
          <a-button @click="onCancel">取消</a-button>
          <a-button type="primary" :disabled="!formBattalion.certificateNo || !formBattalion.dateRange || !fileList.length" @click="onSave">保存</a-button>
        </a-space>
      </a-tab-pane>
    </a-tabs>
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import axios from 'axios'
import dayjs from 'dayjs'
import { post } from '@/utils/request'
import SelectItem from '@/components/SelectItem'

const emit = defineEmits(['update:open', 'update:value', 'success'])
const props = defineProps({
  open: Boolean,
  rowData: {
    type: Object,
    default: () => ({})
  }
})
const tabActiveKey = ref('1')
const rotateDegree = ref(0)
const previewVisible = ref(false)
const previewImage = ref('')
// const previewTitle = ref('')
const selectedRowKey = ref('')
const tableData = ref([])
const fileList = ref([])
const formState = ref({})
const formBattalion = ref({
  dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
})
const { loading, getData } = useTable({
  url: '/optometry/ooadolescentcheck/getOoSupplierCertificateList',
  formatParams: () => {
    return {
      supplierId: formState.value.id,
      pageNum: 1,
      pageSize: 999
    }
  },
  formatResult: (data) => {
    tableData.value = data
    selectedRowKey.value = selectedRowKey.value || data[0].dictCommonCode
  }
})
const getFirstBattalion = async () => {
  const { code, data, msg } = await post('/optometry/ooadolescentcheck/getKcGysCertificate', {
    supplierId: formState.value.id,
    dictCommonCode: selectedRowKey.value
  })
  if (code !== 0) return message.error(msg || '请求失败')
  if (!data) return
  formBattalion.value = { ...formBattalion.value, ...data }
  formBattalion.value.dateRange[0] = data.beginDate
  formBattalion.value.dateRange[1] = data.endDate
  fileList.value = []
  data.certificateUrl1 &&
    fileList.value.push({
      uid: '1',
      name: data.certificateUrl1,
      status: 'done',
      url: data.certificateName1
    })
  data.certificateUrl2 &&
    fileList.value.push({
      uid: '2',
      name: data.certificateUrl2,
      status: 'done',
      url: data.certificateName2
    })
  data.certificateUrl3 &&
    fileList.value.push({
      uid: '3',
      name: data.certificateUrl3,
      status: 'done',
      url: data.certificateName3
    })
}

// 上传
const beforeUpload = async (options) => {
  const { file } = options
  const isJpgOrPng = file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg'
  if (!isJpgOrPng) {
    message.error('请上传jpg或者png格式!')
    fileList.value = fileList.value.filter((item) => {
      return !item.type
    })
    return
  }
  const isLt2M = file.size / 1024 / 1024 < 10
  if (!isLt2M) {
    message.error('上传文件最大10MB!')
    return
  }
  const formData = new FormData()
  formData.append('file', file)
  fileList.value = fileList.value.filter((item) => {
    return item.url
  })
  const { data: res } = await axios.post('/api/v1/common/util/doUploadFile', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
  if (res.code !== 0) return message.error(res.msg)
  if (fileList.value.length !== 3) {
    fileList.value.push({
      uid: fileList.value.length,
      name: res.data.fileName,
      status: 'done',
      url: res.data.picturePath
    })
  }
}

// 预览图片
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}
const handleCancel = () => {
  previewVisible.value = false
  // previewTitle.value = ''
}
const handlePreview = async (file) => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj)
  }
  previewImage.value = file.url || file.preview
  previewVisible.value = true
  // previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
}
const getPyjm = async (name) => {
  const res = await post('/common/util/getPinyin', { name })
  if (res.code === 0) {
    formState.value.zjm = res.data
  }
}
// 基本信息
const onOk = async () => {
  const res = await post('/optometry/ooadolescentcheck/doSaveSupplierInfo', formState.value)
  if (res.code !== 0) return message.error(res.msg || '失败')
  message.success('保存成功')
  formState.value.id = res.data.id
}

// 首营资质
const onSave = async () => {
  const res = await post('/optometry/ooadolescentcheck/doSaveOoSupplierCertificate', {
    certificateNo: formBattalion.value.certificateNo,
    beginDate: formBattalion.value.dateRange?.[0],
    endDate: formBattalion.value.dateRange?.[1],
    certificateUrl1: fileList.value[0]?.name || '',
    certificateUrl2: fileList.value[1]?.name || '',
    certificateUrl3: fileList.value[2]?.name || '',
    dictCommonCode: selectedRowKey.value,
    supplierId: formState.value.id,
    memo: formBattalion.value.memo,
    id: formBattalion.value.id
  })
  if (res.code !== 0) return message.error(res.msg || '失败')
  message.success('保存成功')
  getData()
  getFirstBattalion()
}

// const handlerRotate = () => {
//   rotateDegree.value += 90
// }

const onCancel = () => {
  emit('update:open', false)
  tabActiveKey.value = '1'
  selectedRowKey.value = ''
  formState.value = {}
  formBattalion.value = {}
  fileList.value = []
  emit('success')
}

watch(
  () => props.open,
  (val) => {
    if (val) {
      formState.value = { ...props.rowData }
      tabActiveKey.value = props.rowData.active
    }
  }
)
watch(
  () => tabActiveKey.value,
  () => {
    if (tabActiveKey.value === '2') {
      getData()
    }
  }
)
watch(
  () => selectedRowKey.value,
  (val) => {
    if (val) {
      formBattalion.value = {
        dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
      }
      fileList.value = []
      getFirstBattalion()
    }
  }
)
</script>
<style lang="less" scoped>
.tab-overflow {
  :deep(.ant-tabs-content-holder) {
    overflow: hidden !important;
  }
}
</style>
